<template>
  <input type="text" v-bind="$attrs" @input="handleInput" @focus ="handleFocus" @blur="handleBlur" @change="handleChange" ref="input">
</template>
<script>
export default {
  props: {
    value: [String, Number],
    isNumber: [Boolean],
    toFixed: [Number],
  },
  data() {
    return {
      currentValue: this.value,
      saveValue: "",
      focused: false,
      NumberPattern: new RegExp(
        `^(\\-\|\\+)?\\d+(\\.|\\.\\d${
          this.toFixed && this.toFixed >= 0 ? "{0," + this.toFixed + "}" : "+"
        })?$`
      )
    };
  },
  watch: {
    value(val, oldVal) {
      console.log(val);
    },
    nativeInputValue() {
      this.setNativeInputValue();
    },
  },
  computed: {
    nativeInputValue() {
      return this.value === null || this.value === undefined
        ? ""
        : String(this.value);
    }
  },
  mounted(){
    this.setNativeInputValue();
  },
  methods: {
    handleChange(event) {
        this.$emit('change', event.target.value);
      },
    handleFocus(event) {
      this.focused = true;
      this.$emit('focus', event);
    },
    handleBlur(event) {
      this.focused = false;
      this.$emit('blur', event);
    },
    handleInput(event) {
      if (event.target.value === this.nativeInputValue) return;
      let val = event.target.value;
      if (this.isNumber == true) {
        if (this.NumberPattern.test(val)) {
          this.saveValue = val;
        } else {
          if (val != "") {
            val = this.saveValue;
          }
        }
      }
      this.saveValue = val;
      this.$emit("input", this.saveValue);
      this.$nextTick(this.setNativeInputValue);
    },
    setNativeInputValue() {
      const input = this.getInput();
      if (!input) return;
      if (input.value === this.nativeInputValue) return;
      input.value = this.nativeInputValue;
    },
    getInput() {
      return this.$refs.input;
    }
  }
};
</script>

